package com.ruoyi.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.BhPostInspection;
import com.ruoyi.web.domain.BhPostInspectionBill;
import com.ruoyi.web.domain.BhRiskPost;
import com.ruoyi.web.domain.PostCheckBill;
import com.ruoyi.web.domain.query.AddPostCheckQuery;
import com.ruoyi.web.domain.query.PostCheckPageQuery;
import com.ruoyi.web.domain.vo.PostCheckVO;
import com.ruoyi.web.mapper.BhPostInspectionBillMapper;
import com.ruoyi.web.mapper.BhPostInspectionMapper;
import com.ruoyi.web.mapper.BhRiskPostMapper;
import com.ruoyi.web.service.BhPostCheckService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class BhPostCheckServiceImpl implements BhPostCheckService {
    @Autowired
    private BhPostInspectionMapper bhPostInspectionMapper;
    @Autowired
    private BhPostInspectionBillMapper bhPostInspectionBillMapper;
    @Autowired
    private BhRiskPostMapper bhRiskPostMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 新增岗位检察 - app
     *
     * @param addPostCheckQuery 新增数据
     * @return 返回
     */
    @Transactional
    @Override
    public R<Void> addPostCheck(AddPostCheckQuery addPostCheckQuery) {
        BhPostInspection addPostParam = new BhPostInspection();
        BeanUtils.copyProperties(addPostCheckQuery, addPostParam);
        Long userId = LoginHelper.getUserId();
        addPostParam.setDelFlag(0);                             // 未删除
        addPostParam.setCreateTime(new Date());
        addPostParam.setCreatedBy(String.valueOf(userId));      // 创建人
        addPostParam.setCommitUser(String.valueOf(userId));     // 提交人
        addPostParam.setTeamName(String.valueOf(userId));       // 作业队
        // 检查项列表
        List<PostCheckBill> postCheckBills = addPostCheckQuery.getPostCheckBills();
        Integer checkNum = 0;
        Integer dangerNum = 0;
        if (!CollectionUtils.isEmpty(postCheckBills)) {
            checkNum = postCheckBills.size();
            for (PostCheckBill postCheckBill : postCheckBills) {
                if ("2".equals(postCheckBill.getInspectResult())) {
                    dangerNum++;
                }
            }
        }
        addPostParam.setCheckNum(checkNum);                     // 检查数
        addPostParam.setDangerNum(dangerNum);                   // 隐患数
        addPostParam.setStatus(dangerNum > 0 ? "0" : "1");      // 0-未整改 1-已整改
        bhPostInspectionMapper.insert(addPostParam);
        // 新增检查项目详细数据
        for (PostCheckBill postCheckBill : postCheckBills) {
            BhPostInspectionBill addBillParam = new BhPostInspectionBill();
            BeanUtils.copyProperties(postCheckBill, addBillParam);
            addBillParam.setInspectionId(addPostParam.getId());
            addBillParam.setDelFlag(0);
            addBillParam.setCreateTime(new Date());
            addBillParam.setCreatedBy(String.valueOf(userId));
            bhPostInspectionBillMapper.insert(addBillParam);
        }
        return R.ok();
    }

    /**
     * 分页查询岗位检查数据
     *
     * @param postCheckPageQuery 查询条件
     * @param pageQuery          分页参数
     * @return 岗位检查分页数据
     */
    @Override
    public TableDataInfo<PostCheckVO> getPostCheckPage(PostCheckPageQuery postCheckPageQuery, PageQuery pageQuery) {
        LambdaQueryWrapper<BhPostInspection> lqw = buildQueryWrapper(postCheckPageQuery);
        Page<PostCheckVO> result = bhPostInspectionMapper.selectVoPage(pageQuery.build(), lqw);
        List<PostCheckVO> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (PostCheckVO record : records) {
                fillData(record);
            }
        }
        return TableDataInfo.build(result);
    }

    // 填充作业队
    private void fillData(PostCheckVO record) {
        Long userId = Long.valueOf(record.getTeamName());
        SysUser sysUser = userService.selectUserById(userId);
        if (!Objects.isNull(sysUser)) {
            record.setTeamName(sysUser.getNickName());
        }
    }

    // 组装分页查询条件
    private LambdaQueryWrapper<BhPostInspection> buildQueryWrapper(PostCheckPageQuery postCheckPageQuery) {
        LambdaQueryWrapper<BhPostInspection> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(postCheckPageQuery.getTeamName()), BhPostInspection::getTeamName, postCheckPageQuery.getTeamName());
        lqw.like(StringUtils.isNotBlank(postCheckPageQuery.getWellNo()), BhPostInspection::getWellNo, postCheckPageQuery.getWellNo());
        lqw.like(StringUtils.isNotBlank(postCheckPageQuery.getTeamGroup()), BhPostInspection::getTeamGroup, postCheckPageQuery.getTeamGroup());
        lqw.eq(StringUtils.isNotBlank(postCheckPageQuery.getShiftLeader()), BhPostInspection::getShiftLeader, postCheckPageQuery.getShiftLeader());
        lqw.eq(StringUtils.isNotBlank(postCheckPageQuery.getStatus()), BhPostInspection::getStatus, postCheckPageQuery.getStatus());
        lqw.orderByDesc(BhPostInspection::getCreateTime);
        return lqw;
    }

    /**
     * 获取岗位检查详情
     *
     * @param id 岗位检查id
     * @return 岗位检查详情
     */
    @Override
    public R<PostCheckVO> getPostCheckDetail(Integer id) {
        PostCheckVO result = new PostCheckVO();
        List<PostCheckBill> bills = new ArrayList<>();
        BhPostInspection bhPostInspection = bhPostInspectionMapper.selectById(id);
        if (Objects.isNull(bhPostInspection)) {
            return R.fail("未找到对应的岗位检查!");
        }
        BeanUtils.copyProperties(bhPostInspection, result);
        fillLiveProjects(result);
        List<BhPostInspectionBill> bhPostInspectionBills = bhPostInspectionBillMapper.selectList(new LambdaQueryWrapper<BhPostInspectionBill>().eq(BhPostInspectionBill::getDelFlag, 0).eq(BhPostInspectionBill::getInspectionId, id));
        if (!CollectionUtils.isEmpty(bhPostInspectionBills)) {
            for (BhPostInspectionBill bhPostInspectionBill : bhPostInspectionBills) {
                PostCheckBill postCheckBill = new PostCheckBill();
                BeanUtils.copyProperties(bhPostInspectionBill, postCheckBill);
                bills.add(postCheckBill);
            }
        }
        result.setPostCheckBills(bills);
        fillData(result);
        return R.ok(result);
    }

    // 填充现场检查项目
    private void fillLiveProjects(PostCheckVO postCheck) {
        List<String> liveProjectNames = new ArrayList<>();
        List<String> liveProjectList = com.ruoyi.common.utils.StringUtils.str2List(postCheck.getLiveProjects(), "[|]", true, true);
        if (CollUtil.isNotEmpty(liveProjectList)) {
            for (String liveProjectId : liveProjectList) {
                BhRiskPost bhRiskPost = bhRiskPostMapper.selectById(liveProjectId);
                if (!Objects.isNull(bhRiskPost)) {
                    liveProjectNames.add(bhRiskPost.getName());
                }
            }
            postCheck.setLiveProjects(liveProjectNames.stream().reduce((s1, s2) -> s1 + "|" + s2).orElse(""));
        }
    }

    /**
     * 编辑岗位检查
     *
     * @param addPostCheckQuery 修改数据
     * @return 返回
     */
    @Transactional
    @Override
    public R<Void> modPostCheck(AddPostCheckQuery addPostCheckQuery) {
        List<PostCheckBill> postCheckBills = addPostCheckQuery.getPostCheckBills();
        List<Integer> billIds = new ArrayList<>();
        for (PostCheckBill postCheckBill : postCheckBills) {
            billIds.add(postCheckBill.getId());
            BhPostInspectionBill modBillParam = new BhPostInspectionBill();
            BeanUtils.copyProperties(postCheckBill, modBillParam);
            bhPostInspectionBillMapper.updateById(modBillParam);
        }
        List<BhPostInspectionBill> bhPostInspectionBills = bhPostInspectionBillMapper.selectList(new LambdaQueryWrapper<BhPostInspectionBill>().eq(BhPostInspectionBill::getDelFlag, 0).eq(BhPostInspectionBill::getInspectionId, addPostCheckQuery.getId()).notIn(BhPostInspectionBill::getId, billIds));
        boolean flag = true;
        if (!CollectionUtils.isEmpty(bhPostInspectionBills)) {
            for (BhPostInspectionBill bhPostInspectionBill : bhPostInspectionBills) {
                if (StringUtils.isBlank(bhPostInspectionBill.getRectifyPhotosAfter())) {
                    flag = false;
                }
            }
        }
        if (flag) {
            BhPostInspection modParam = new BhPostInspection();
            modParam.setId(addPostCheckQuery.getId());
            modParam.setStatus("1");
            bhPostInspectionMapper.updateById(modParam);
        }
        return R.ok();
    }

    /**
     * 获取岗位检查隐患列表
     *
     * @param id 岗位检查id
     * @return 隐患列表
     */
    @Override
    public R<List<PostCheckBill>> getDangerList(Integer id) {
        List<PostCheckBill> result = new ArrayList<>();
        List<BhPostInspectionBill> bhPostInspectionBills = bhPostInspectionBillMapper.selectList(new LambdaQueryWrapper<BhPostInspectionBill>().eq(BhPostInspectionBill::getDelFlag, 0).eq(BhPostInspectionBill::getInspectionId, id).eq(BhPostInspectionBill::getInspectResult, "2"));
        if (!CollectionUtils.isEmpty(bhPostInspectionBills)) {
            for (BhPostInspectionBill bhPostInspectionBill : bhPostInspectionBills) {
                PostCheckBill postCheckBill = new PostCheckBill();
                BeanUtils.copyProperties(bhPostInspectionBill, postCheckBill);
                result.add(postCheckBill);
            }
        }
        return R.ok(result);
    }

    /**
     * 获取现场检查项目数据
     *
     * @return 全量的项目检查数据
     */
    @Override
    public R<List<BhRiskPost>> getAllRiskPost() {
        return R.ok(bhRiskPostMapper.selectList(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0)));
    }
}
